package com.study.controller;


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.json.JsonWriteContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.study.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

//@Controller 走调节视图控制器
//@RestController 前后端分离，只返回字符串
@RestController
public class UserController {

    //@RequestMapping(value = "/json",produces = "application/json;charset=utf-8") 解决json中文乱码，可以在spring配置文件中配置
    @RequestMapping("/json")
    //@ResponseBody  @RestController 前后端分离，只返回字符串 不需要了
    public String jsonTest() throws JsonProcessingException {

        User user = new User(1,"中文");

        ObjectMapper mapper = new ObjectMapper();
        String str = mapper.writeValueAsString(user);

        return str;
    }

    //@RequestMapping(value = "/json",produces = "application/json;charset=utf-8") 解决json中文乱码，可以在spring配置文件中配置
    @RequestMapping("/json2")
    //@ResponseBody  @RestController 前后端分离，只返回字符串 不需要了
    public String jsonTest2() throws JsonProcessingException {

        User user1 = new User(1,"中文");
        User user2 = new User(1,"中文");
        User user3 = new User(1,"中文");
        User user4 = new User(1,"中文");

        ObjectMapper mapper = new ObjectMapper();
        List<User> userList = new ArrayList<User>();
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);

        String str = mapper.writeValueAsString(userList);

        return str;
    }

    //@RequestMapping(value = "/json",produces = "application/json;charset=utf-8") 解决json中文乱码，可以在spring配置文件中配置
    @RequestMapping("/json3")
    //@ResponseBody  @RestController 前后端分离，只返回字符串 不需要了
    public String jsonTest3() throws JsonProcessingException {

        User user1 = new User(1,"中文");
        User user2 = new User(1,"中文");
        User user3 = new User(1,"中文");
        User user4 = new User(1,"中文");

        List<User> userList = new ArrayList<User>();
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);

        return JSON.toJSONString(userList);
    }
}
